package Threaddemo.thread_0910;

class MyBlockingQueue {
    private String[] data = new String[1000];
    private volatile int head = 0;
    private volatile int tail = 0;
    private volatile int size = 0;

    public MyBlockingQueue() {}

    public synchronized void put (String elem) throws InterruptedException {
        while (isfull()) {
            this.wait();
            //使用while循环,因为可能是 interrupt 唤醒
        }
//        if (isfull()) {
//            this.wait();
//        }
        data[tail] = elem;
        tail++;
        if (tail == data.length) {
            tail = 0;
        }
        size++;
        //唤醒take中的wait
        this.notify();
    }

    public synchronized String take() throws InterruptedException {
        while (size == 0) {
            this.wait();
        }

//        if (size == 0) {
//            this.wait();
//        }
        String ret = data[head];
        head++;
        if (head == data.length) {
            head = 0;
        }
        size--;
        this.notify();
        return ret;
    }


    public boolean isfull() {
        return size == data.length;
    }
}

public class demo1_0515 {
    public static void main(String[] args) throws InterruptedException {
        MyBlockingQueue queue = new MyBlockingQueue();
        Thread t1 = new Thread(()->{
            //消费者
            while (true) {
                try {
                    String result = queue.take();
                    System.out.println("消费元素："+result);
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });

        //生产者
        Thread t2 = new Thread(()->{
            int n = 1;
            while (true) {
                try {
                    queue.put(n+"");
                    System.out.println("生产元素：" + n);
                    n++;
                    n = n % 1000;
//                    Thread.sleep(500);

                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        });
        t1.start();
        t2.start();

    }
}